import { User, UserDocument } from '@app/database/schemas/user.schema';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class UsersService {
  constructor(
    @InjectModel('User') private readonly userModel: Model<UserDocument>,
  ) {}

  create(user: User) {
    return this.userModel.create(user);
  }

  async findAll(query: any) {
    let { size, currentPage } = query || {};
    size = Number(size);
    currentPage = Number(currentPage);
    const res = await this.userModel
      .find()
      .skip((currentPage - 1) * size)
      .limit(size)
      .sort({ _id: -1 });
    const total = await this.userModel.countDocuments();
    return {
      items: res,
      total,
    };
  }

  findOne(id: string) {
    return this.userModel.findOne({ _id: id });
  }

  update(id: string, user: User) {
    return this.userModel.updateOne({ _id: id }, user);
  }

  remove(id: string) {
    return this.userModel.deleteOne({ _id: id });
  }

  option() {
    return {
      title: '用户列表',
      descriptions: '显示和处理用户列表',
      items: [
        {
          label: '用户名',
          prop: 'username',
          type: 'input',
        },
        {
          label: '密码',
          prop: 'password',
          type: 'input',
          display: true,
        },
        {
          label: '电话',
          prop: 'tel',
          type: 'input',
        },
        {
          label: '地址',
          prop: 'address',
          type: 'input',
        },
        {
          label: '权限',
          prop: 'grant',
          type: 'select',
          keyName: 'name',
          items: [
            {
              name: '用户',
              _id: 0,
            },
            {
              name: '管理员',
              _id: 1,
            },
          ],
        },
      ],
    };
  }
}
